using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MMM.Core.Domain;
using ServiceStack.ServiceHost;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using MMM.Services.Base;
using MMM.Services.Operations;
using MMM.Services.Type;
using ServiceStack.ServiceInterface;
using MMM.Core;
using MMM.Services.Response;
using ServiceStack.CacheAccess;
using MMM.Services.Expansion;
using ServiceStack.ServiceInterface.Auth;

namespace MMM.Services
{

    public class UserService : BaseService<User>
    {
        public override object OnPost(User request)
        {
            if (request != null)
            {
                string hash = CommonFunction.Commonfunction.GetMD5Str(request.Slat + "hash");
                string salt = CommonFunction.Commonfunction.GetMD5Str(request.Slat + "salt");
                //new SaltedHash().GetHashAndSaltString(request.Slat, out hash, out salt);
                request.Slat = salt;
                request.PasswordHash=hash;
            }
            return base.OnPost(request);
        }
    }

    public class UserGetSerice : BaseGetService<UserPageGet, User>
    {
        protected override String CreateFilter(UserPageGet request)
        {
            //var session = (MyUserSession)this.GetSession(false)
            //string name = session.FirstName;
            string s = "";
            IList<Filter> lst = request.GetFilter();
            if (lst == null)
            {
                return string.Empty;
            }
            foreach (var item in lst)
            {
                if (item.Property == "DepartID")
                {
                    item.Value = Guid.Parse(item.Value).ToString();
                    if (string.IsNullOrEmpty(s))
                    {
                        s = item.ToSqlEque();
                    }
                    else
                    {
                        s = string.Format("{0} and {1}", s, item.ToSqlEque());
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(s))
                    {
                        s = item.ToSqlLike();
                    }
                    else
                    {
                        s = string.Format("{0} and {1}", s, item.ToSqlLike());
                    }
                }
            }

            if (request.isLock.HasValue)
            {
                if (!string.IsNullOrWhiteSpace(s))
                {
                    s += " and ";
                }
                return s + "Flag =" + request.isLock;
            }
            return s;
        }
    }


    public class UserCheckService : BaseService<UserCheck>
    {
        public override object OnGet(UserCheck request)
        {
            IRepository<User> userRep = ApplicationContext.Container.GetInstance<IRepository<User>>();

            return new OperationResult<User>(userRep.GetEntities(1, 1, " Name='" + request.userName + "'"));
            //return OperationResult<User>.SuccessRespose;
        }
        public override object OnPost(UserCheck request)
        {
            if (string.IsNullOrEmpty(request.userName) && string.IsNullOrEmpty(request.userPwd))
            {
                this.RemoveSession();
                return null;
            }

            //bool isUser = MMM.Services.Services.Sys.ConfigUserService.IsConfigUser();

            IRepository<User> userRep = ApplicationContext.Container.GetInstance<IRepository<User>>();
            IRepository<Shop> shopRep = ApplicationContext.Container.GetInstance<IRepository<Shop>>();
            string hash = CommonFunction.Commonfunction.GetMD5Str(request.userPwd + "hash");
            string salt = CommonFunction.Commonfunction.GetMD5Str(request.userPwd + "salt");
            //new SaltedHash().GetHashAndSaltString(request.userPwd, out hash, out salt);
            var userList = userRep.GetAll(t => t.Name == request.userName);
            if (userList.Count() == 0)
            {
                return OperationResult<User>.FailureResponse("0");
            }
            else
            {
                if (userList.First().Flag == 1)
                {
                    return OperationResult<User>.FailureResponse("2");
                }
                if (salt == userList.First().Slat && hash == userList.First().PasswordHash)
                {

                    var session = (MyUserSession)this.GetSession(false);
                    session.UserName = request.userName;
                    session.UserPwd = request.userPwd;
                    session.IsAuthenticated = true;
                    session.UserID = userList.First().Id;
                    session.IsAuthenticated = MMM.Services.Services.Sys.ConfigUserService.IsConfigUser();
                    if (userList.First().Name == "admin")
                    {
                        session.ShopList = shopRep.GetAll(t => t.Flag == 0).ToList();
                    }
                    else
                    {
                        session.ShopList = shopRep.GetAll(t => t.Fperson == userList.First().Name && t.Flag == 0).ToList();
                    }
                    this.SaveSession(session);
                    return OperationResult<User>.SuccessRespose;
                }
                else
                {
                    return OperationResult<User>.FailureResponse("1");
                }
            }
        }
    }

    //public class MyUserSession : AuthUserSession
    //{
    //    public List<Shop> ShopList { get; set; }
    //    public string UserPwd { get; set; }
    //    public Guid? UserID { get; set; }
    //}

    //public class MyCredentialsAuthProvider : CredentialsAuthProvider
    //{
    //    //
    //    List<User> userList = null;
    //    public override bool TryAuthenticate(IServiceBase authService, string userName, string userPwd)
    //    {
    //        if (!CheckInDB(userName, userPwd)) return false;
    //        IRepository<Shop> shopRep = ApplicationContext.Container.GetInstance<IRepository<Shop>>();
    //        var session = (MyUserSession)authService.GetSession(false);
    //        session.UserName = userName;
    //        session.UserPwd = userPwd;
    //        //new SaltedHash().GetHashAndSaltString(Password, out hash, out salt);
    //        session.IsAuthenticated = true;
    //        session.UserID = userList.First().Id;
    //        if (userList.First().Name == "admin")
    //        {
    //            session.ShopList = shopRep.GetAll(t => t.Flag == 0).ToList();
    //        }
    //        else
    //        {
    //            session.ShopList = shopRep.GetAll(t => t.Fperson == userList.First().Name && t.Flag == 0).ToList();
    //        }

    //        // add roles 
    //        session.Roles = new List<string>();
    //        if (session.UserAuthId == "admin") session.Roles.Add(RoleNames.Admin);
    //        session.Roles.Add("User");
    //        //this.SaveSession(session);
    //        //return OperationResult<User>.SuccessRespose;

    //        return true;
    //    }

    //    private bool CheckInDB(string userName, string userPwd)
    //    {
    //        IRepository<User> userRep = ApplicationContext.Container.GetInstance<IRepository<User>>();
    //        string hash = string.Empty;
    //        string salt = string.Empty;
    //        new SaltedHash().GetHashAndSaltString(userPwd, out hash, out salt);
    //        userList = userRep.GetAll(t => t.Name == userName).ToList();
    //        if (userList.Count() == 0)
    //        {
    //            //return OperationResult<User>.FailureResponse("0");
    //            return false;
    //        }
    //        else
    //        {
    //            if (userList.First().Flag == 1)
    //            {
    //                //return OperationResult<User>.FailureResponse("2");
    //                return false;
    //            }
    //            if (salt == userList.First().Slat && hash == userList.First().PasswordHash)
    //            {
    //                return true;
    //            }
    //        }
    //        return false;
    //    }
    //}
}
